/*------------------------------------------------------------------------------*\
**   Copyright 2008-2009 Jonhnny Weslley                                        **
**                                                                              **
**   Licensed under the Apache License, Version 2.0 (the "License");            **
**   you may not use this file except in compliance with the License.           **
**   You may obtain a copy of the License at                                    **
**                                                                              **
**       http://www.apache.org/licenses/LICENSE-2.0                             **
**                                                                              **
**   Unless required by applicable law or agreed to in writing, software        **
**   distributed under the License is distributed on an "AS IS" BASIS,          **
**   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   **
**   See the License for the specific language governing permissions and        **
**   limitations under the License.                                             **
\*------------------------------------------------------------------------------*/

package org.scalashell.commands

import jline._
import org.scalashell.{ShellSystem, SimpleCommandSupport}
import ShellSystem.{messages => %}

class HelpCommand(name: String) extends SimpleCommandSupport(name) {

  execute { args =>
    args match {
      case Nil => list()
      case List(command) => help(command)
      case _ => fail("Unexpected arguments: " + args)
    }
  }

  def help(commandName: String) {
    ShellSystem getCommand commandName match {
      case Some(command) => {
        println(command)
      }
      case None => fail("No such command: " + commandName)
    }
  }

  def list() {
    val byName = (c1: Command, c2: Command) => c1.name < c2.name
    val commands = ShellSystem.commands.toList.sort(byName)
    println(%("help.header"))

    println(commands.foldLeft("") {
          (help, command) => help + "\n" + %("help.format.command", command.name)
    })

    println(%("help.footer"))
  }

  override protected def createCompletors: Option[List[Completor]] = {
    val cmdCompletor = new SimpleCompletor(new Array[String](0))
    ShellSystem.commands foreach (c => cmdCompletor addCandidateString c.name)
    Some(cmdCompletor :: Nil)
  }

}
